package com.omenkk.juc.ReentrantLock;

import com.omenkk.juc.util.Slepper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

///锁超时
//获取锁获取失败，直接立刻返回/等待一段时间后，如果没有获取，返回
    @Slf4j
public class demo3 {
    public static void main(String[] args) {
        //创建锁
        ReentrantLock lock=new ReentrantLock();
        Thread t1=new Thread(()->{
            try {
                if(!lock.tryLock(3, TimeUnit.SECONDS)) {
        //  if(!lock.tryLock()) {  //获取不到锁立即释放
              //如果获取锁失败
              log.debug("获取锁失败，返回");
              return;
          }
            } catch (InterruptedException e) {
               e.printStackTrace();
            }
            try{
          log.debug("获取了锁");
      }finally {
                log.debug("释放锁");
          lock.unlock();
      }
        });
        lock.lock();
        t1.start();
        try{
            Slepper.sleep(1);
        }finally {
            lock.unlock();
        }
    }
}
